package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.framework.DefaultAdvisorChainFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 锋哥
 * @since 2022-11-16
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
   @Autowired
   private SeckillVoucherMapper seckillVoucherMapper;
   @Autowired
   private IVoucherOrderService voucherOrderService;
   @Autowired
   private RedisIdWorker redisIdWorker;
   @Autowired
   private StringRedisTemplate stringRedisTemplate;
   @Autowired
   private RedissonClient redissonClient;
//   private static final DefaultRedisScript<Long> SECKIL_SCRIPT;
//   static {
//       SECKIL_SCRIPT=new DefaultRedisScript<>();
//       SECKIL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
//       SECKIL_SCRIPT.setResultType(Long.class);
//   }
//   //定义阻塞队列
//   private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
//   //创建线程池
//   private ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
//
//   @PostConstruct
//   private void init(){
//       SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//   }
//   //线程任务
//    public class VoucherOrderHandler implements  Runnable{
//       @Override
//       public void run() {
//          while(true){
//              //1.获取队列中的订单信息
//              try {
//                  VoucherOrder voucherOrder = orderTasks.take();
//                  //创建订单
//                  handleVoucherOrder(voucherOrder);
//              } catch (Exception e) {
//                  log.error("处理订单异常",e);
//              }
//
//          }
//       }
//   }

//    private void handleVoucherOrder(VoucherOrder voucherOrder) {
//        RLock lock = redissonClient.getLock("lock:order:" + voucherOrder.getUserId());
//
//        //尝试获取锁对象
////        boolean isLock = simpleRedisLock.tryLock(1200);
//        boolean isLock = lock.tryLock();
//        if (!isLock) {
//            //获取锁失败
//            log.error("不允许重复下单");
//            return;
//        }
//        try {
//
//            return proxy.createVoucherOrder(voucherId, seckillVoucher);
//        } finally {
//            //成不成功，都要释放锁
//            lock.unlock();
//        }
////        }
//
//    }
   private IVoucherOrderService proxy;
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//       //获取用户id
//        Long id = UserHolder.getUser().getId();
//        //基于优惠券id进行优惠券查询
//        SeckillVoucher seckillVoucher = seckillVoucherMapper.selectById(voucherId);
//        //得到开始时间判断是否已经开始
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        long second = beginTime.toEpochSecond(ZoneOffset.UTC);
//        //当前时间
//        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
//        if (second - now > 0) {
//            //证明抢券还未开始
//            return Result.fail("该券还未开始抢购!");
//        }
//        //判断是否已经结束
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        long end = endTime.toEpochSecond(ZoneOffset.UTC);
//
//        if (now - end > 0) {
//            return Result.fail("该券抢购时间已过!");
//        }
//        //1.执行lua脚本
//        Long result = stringRedisTemplate.execute(
//                SECKIL_SCRIPT, Collections.emptyList(), voucherId.toString()
//                , id.toString()
//        );
//        //2.判断结果是否为0
//        if(result.intValue()==1){
//            //3.不是0，没有购买资格，返回异常信息
//            //库存不足
//            return Result.fail("库存不足");
//        }
//        if(result.intValue()==2){
//            return Result.fail("请勿重复下单");
//        }
//
//            //4.为0，有购买资格，把下单信息保存到阻塞队列
//            long orderId = redisIdWorker.nextId("order");
//            VoucherOrder voucherOrder=new VoucherOrder();
//            voucherOrder.setId(orderId);
//            //设置套餐id
//            voucherOrder.setVoucherId(voucherId);
//            //设置用户id
//            voucherOrder.setUserId(UserHolder.getUser().getId());
//            //创建阻塞队列
//            orderTasks.add(voucherOrder);
//
//            //
//       proxy = (IVoucherOrderService)AopContext.currentProxy();
//
//        //5.返回订单id
//
//        return Result.ok(orderId);
//    }

     public Result seckillVoucher(Long voucherId) {
        //基于优惠券id进行优惠券查询
        SeckillVoucher seckillVoucher = seckillVoucherMapper.selectById(voucherId);
        //得到开始时间判断是否已经开始
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        long second = beginTime.toEpochSecond(ZoneOffset.UTC);
        //当前时间
        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        if (second - now > 0) {
            //证明抢券还未开始
            return Result.fail("该券还未开始抢购!");
        }
        //判断是否已经结束
        LocalDateTime endTime = seckillVoucher.getEndTime();
        long end = endTime.toEpochSecond(ZoneOffset.UTC);

        if (now - end > 0) {
            return Result.fail("该券抢购时间已过!");
        }

        //判断库存是否充足
        Integer stock = seckillVoucher.getStock();
        if (stock <= 0) {
            return Result.fail("库存不足");
        }

        //先要让事务进行提交在释放锁，所以synchronized要加在执行方法之前
        //锁的条件是同一个用户，所以用用户id进行加锁，intern是在常量池寻找指定的字面量，返回该对象的地址
        //这种做法是单体项目的做法，无法解决集群多线程问题
//        synchronized (UserHolder.getUser().getId().toString().intern()) {
        //获取代理对象(事务)
        //由于直接调用createVoucherOrder，事务会失效（方法内部调用，事务会失效）
        //这里相当于this.createVoucherOrder，this为VoucherOrderServiceImpl,其本身不是代理对象

        //用简单分布式锁解决多线程一人一单的问题
        //创建锁对象

//        SimpleRedisLock simpleRedisLock = new SimpleRedisLock(stringRedisTemplate, "order:" + UserHolder.getUser().getId());
        RLock lock = redissonClient.getLock("lock:order:" + UserHolder.getUser().getId());

        //尝试获取锁对象
//        boolean isLock = simpleRedisLock.tryLock(1200);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            //获取锁失败
            return Result.fail("不允许重复抢券");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId, seckillVoucher);
        } finally {
            //成不成功，都要释放锁
            lock.unlock();
        }
//        }


    }
    @Transactional
    public  Result createVoucherOrder(Long voucherId,SeckillVoucher seckillVoucher) {
        //库存充足 ,需要判断用户是否已经下过单了
            LambdaQueryWrapper<VoucherOrder> voucherOrderLambdaQueryWrapper=new LambdaQueryWrapper<>();
            //根据用户id和voucherid进行查询
            //sql select * from tb_voucher_order where user_id=当前user_id and voucher_id =当前voucherid
            voucherOrderLambdaQueryWrapper.eq(VoucherOrder::getUserId,UserHolder.getUser().getId());
            voucherOrderLambdaQueryWrapper.eq(VoucherOrder::getVoucherId,voucherId);
            int count = this.count(voucherOrderLambdaQueryWrapper);
            if(count>0){
                return Result.fail("你已抢过该券");
            }

            LambdaQueryWrapper<SeckillVoucher> queryWrapper = new LambdaQueryWrapper<>();
            //sql set stock-1 from 表 where stock=当前stock id=当前id
            //存在弊端，成功率太低，乐观锁认为有人修改了值就是线程不安全，但是实际业务库存还有
            //改进:
            //sql set stock-1 from 表 where stock>0 id=当前id  只要库存大于0，能查出该对象，证明可以执行减库存的语句
            queryWrapper.gt(SeckillVoucher::getStock, 0);
            queryWrapper.eq(SeckillVoucher::getVoucherId, voucherId);
            //判断sql语句是否能查出该对象，如果查不出来，证明库存已经被另外一个线程修改(这里的业务是证明库存已经不是>0)
            SeckillVoucher newseckillVoucher = seckillVoucherMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(newseckillVoucher)) {
                //证明已经被另外一个线程修改
                seckillVoucher.setStock(seckillVoucher.getStock() - 1);
                seckillVoucherMapper.updateById(seckillVoucher);

                //创建订单表
                VoucherOrder voucherOrder = new VoucherOrder();
                //订单id，用全局id生成器生成
                long order = redisIdWorker.nextId("order");
                voucherOrder.setId(order);
                //设置套餐id
                voucherOrder.setVoucherId(voucherId);
                //设置用户id
                voucherOrder.setUserId(UserHolder.getUser().getId());
                this.save(voucherOrder);
                return Result.ok(order);
            } else {
                return Result.fail("抢券失败!");
            }
        }

}
